#include <sys/stat.h>
#include <sstream>
#include <unistd.h>

#include "../code/Logger.h"
#include "../code/AsyncLogging.h"

void testLogging()
{
    Logger::Logger::setLogLevel(Logger::Logger::LogLevel::DEBUG);
    LOG_DEBUG << "debug";
    LOG_INFO << "info";
    LOG_WARN << "warn";
    LOG_ERROR << "error";
    // LOG_FATAL << "fatal";    // 程序会终止

    for (int i = 0; i < 10; i++)
    {
        LOG_INFO << "Hello, " << i << " abc...xyz";
    }
}

void testLogging2()
{
    for (int i = 0; i < 1024; ++i)
    {
        LOG_INFO << "Hello, " << i << " abc...xyz";
    }
}

Logger::AsyncLogging *gAsyncLogging = nullptr;
void asyncLogFunc(const char *data, int len)
{
    Logger::AsyncLogging *asyncLogging = gAsyncLogging;
    if (asyncLogging)
    {
        asyncLogging->append(data, len);
    }
}

int main(int argc, char *argv[])
{
    // 当前目录下创建日志文件夹
    std::string logDir = "logs";
    ::mkdir(logDir.c_str(), 0755);

    // 测试文件路径
    std::ostringstream testFilePath{};
    testFilePath << logDir << "/" << ::basename(argv[0]);

    // 测试日志
    testLogging();
    sleep(1);

    Logger::AsyncLogging asyncLogging(testFilePath.str(), 1 * 1024 * 1024); // 滚动大小1MB；asyncLogging在main()中管理
    gAsyncLogging = &asyncLogging;                                          // 所以用gAsyncLogging连接main()和asyncLogFunc()
    Logger::Logger::setOutputFunc(asyncLogFunc);                            // 设置输出回调，实际用asyncLogging->append()
    asyncLogging.start();                                                   // 开始后端刷盘线程

    testLogging();
    testLogging2();
    sleep(3);
    asyncLogging.stop();

    return 0;
}